/**
 * 
 */
package net.looker.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Logger;

import net.looker.config.ConfigManager;

/**
 * MYSQL 查询类
 * 管理与MYSQL连接及查询请求
 * @author solosky
 *
 */
public class MysqlQuery
{
	
	
	/**
	 * 单例模式
	 */
	private static MysqlQuery mysqlQuery;
	
	
	/**
	 * 连接对象
	 */
	private Connection conn;
	
	/**
	 * 结果集合
	 */
	private ResultSet rs;
	
	/**
	 * SQL语句对象
	 */
	private Statement stmt;
	
	/**
	 * 表前缀
	 */
	private String prex;
	
	
	
	/**
	 * 返回单例对象
	 * @return
	 */
	public synchronized static MysqlQuery getInstance()
	{
		if(mysqlQuery==null)
			mysqlQuery = new MysqlQuery();
		return mysqlQuery;
	}
	
	
	/**
	 * 构造函数
	 */
	
	private MysqlQuery()
	{
		//参数
		String host = ConfigManager.getInstance().getLookerConfig().get("data.mysql.host");
		String port = ConfigManager.getInstance().getLookerConfig().get("data.mysql.port");
		String base = ConfigManager.getInstance().getLookerConfig().get("data.mysql.base");
		String user = ConfigManager.getInstance().getLookerConfig().get("data.mysql.user");
		String pass = ConfigManager.getInstance().getLookerConfig().get("data.mysql.pass");
		String prex = ConfigManager.getInstance().getLookerConfig().get("data.mysql.prex");
		String enco = ConfigManager.getInstance().getLookerConfig().get("data.mysql.charset");
		this.prex = prex;
		String sDriver = "com.mysql.jdbc.Driver";
		String surl    = "jdbc:mysql://"+host+":"+port+"/"+base+"?user="+user+"&password="+pass+"&useUnicode=true&characterEncoding="+enco;
		//尝试连接数据库
		try {
			Class.forName(sDriver).newInstance();
			conn = DriverManager.getConnection(surl);
			stmt = conn.createStatement();
		} catch (Exception e) {
			Logger.getLogger("looker").severe("数据库连接初始化错误："+e.getMessage());
		}
	}
	
	/**
	 * 执行更新删除等操作
	 * @param sql
	 * @return
	 * @throws SQLException 
	 */
	public synchronized void execute(String sql) throws SQLException
	{
		sql = formatSql(sql);
		stmt.execute(sql);
		
	}
	
	/**
	 * 执行有数据返回的查询
	 * @param sql
	 * @return
	 * @throws SQLException 
	 */
	public synchronized ResultSet query(String sql) throws SQLException
	{
		sql = formatSql(sql);
		rs = stmt.executeQuery(sql);
		return rs;
	}
	
	/**
	 * 替换掉表前缀
	 * 在SQL用#表示表前缀
	 * @param sql
	 * @return
	 */
	private String formatSql(String sql)
	{
		return sql.replace("#", prex);
	}
	
	
}
